package com.example.flashsales.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.flashsales.config.AliPayConfig;
import com.example.flashsales.entity.Result;
import com.example.flashsales.entity.vo.OrdersVo;
import com.example.flashsales.service.impl.OrderServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    OrderServiceImpl orderService;

    @ResponseBody
    @GetMapping("/alipay")
    public Result payController(HttpServletRequest request, HttpServletResponse response,Long orderId) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST,GET");
        response.addHeader("Access-Control-Expose-Headers","Token");
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.APP_ID, AliPayConfig.APP_PRIVATE_KEY, "json", AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.sign_type);
        if (orderId == null){
            return Result.error("参数不能为空");
        }
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AliPayConfig.return_url+"?orderId="+orderId);
        alipayRequest.setNotifyUrl(AliPayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        final long time = new Date().getTime();
        String out_trade_no = time+"";
        //付款金额，必填
        final List<OrdersVo> ordersVoList = orderService.viewOrder(orderId);
        if (ordersVoList == null || ordersVoList.isEmpty()){
            return Result.error("订单不存在");
        }
        if (ordersVoList.get(0).getState() != 4){
            return Result.error("订单已经付款成功");
        }
        String total_amount = ordersVoList.get(0).getOrderMoney()+"";
        //订单名称，必填
        String subject = ""+orderId;
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
//        response.setContentType("text/html;charset=" + AliPayConfig.CHARSET);
//        response.getWriter().write(form);//直接将完整的表单html输出到页面
//        response.getWriter().flush();
//        response.getWriter().close();
        return Result.ok().setData(form);
    }

}
